import React, { useState, useEffect, useRef } from 'react';
import { connect } from 'umi';
import { Modal, Row, Col, Form, Select, Button, message } from 'antd';
const { Option } = Select;
import styles from './index.less';
import { find } from 'lodash';
/**
 * 设置用户角色。更新用户表。
 * @param props
 * @returns
 */
const UserRoleModel = (props: any) => {
  const {
    dispatch,
    loading,
    visitSetRole,
    setVisitSetRole,
    user,
    fetchUserData,
  } = props;
  const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
  };
  const [form] = Form.useForm();

  const [options, setOptions] = useState([]);
  // const [selectRole, setSelectRole] = useState({});
  // const onChange = (value) => {
  //   options.forEach((item) => {
  //     if (value == item._id) {
  //       setSelectRole(item);
  //     }
  //   });
  // };

  useEffect(() => {
    if (visitSetRole && user && user._id) {
      form.setFieldsValue({
        role: user.role ? JSON.parse(user.role).id : '',
      });
    } else {
      visitSetRole && form.resetFields();
    }
    dispatch({ type: 'enoadRBAC/fetchRolesData', payload: {} }).then((res) => {
      if (res) {
        setOptions(res);
      }
    });
  }, [visitSetRole]);

  const handleCancel = () => {
    setVisitSetRole(false);
  };

  const handleSave = async () => {
    const res = await form.validateFields();
    let parent = find(options, (role) => {
      return role._id === res.role;
    });
    console.log("[res]", res);
    console.log("[res]", parent);
    if (user && user._id) {
      dispatch({
        type: 'enoadRBAC/updateUser',
        payload: { ...user,role:parent ? JSON.stringify({
          id: parent._id,
          name: parent.name,
        }):""},
      }).then((res) => {
        if (res) {
          message.success(res.msg);
          setVisitSetRole(false);
          fetchUserData();
        }
      });
    }
  };

  return (
    <>
      <Modal
        title={'设置角色'}
        destroyOnClose
        visible={visitSetRole}
        width={800}
        getContainer={false}
        maskClosable={false}
        onCancel={handleCancel}
        onOk={handleSave}
        footer={[
          <Button key="back" onClick={handleCancel}>
            取 消
          </Button>,
          <Button
            key="submit"
            loading={loading.effects['enoadRBAC/updateUser']}
            disabled={loading.effects['enoadRBAC/updateUser']}
            type="primary"
            onClick={handleSave}
          >
            确 定
          </Button>,
        ]}
      >
        <Row>
          <Col span={24}>
            <Form form={form}>
              <Form.Item
                {...formItemLayout}
                labelAlign={'left'}
                rules={[{ required: true, message: '请设置用户角色' }]}
                label="角色"
                name="role"
              >
                <Select
                  showSearch
                  placeholder="请设置用户角色"
                  // onChange={onChange}
                >
                  {options &&
                    options.map((item) => {
                      return (
                        <Option key={item._id} value={item._id}>
                          {item.name}
                        </Option>
                      );
                    })}
                </Select>
              </Form.Item>
            </Form>
          </Col>
        </Row>
      </Modal>
    </>
  );
};
//关联到用户权限管理state的models中。
export default connect(({ enoadRBAC, loading }) => ({
  ...enoadRBAC,
  loading,
}))(UserRoleModel);
